package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.IShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <b><code>ShoppingCartServiceImpl</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 29/06/2024 18:36.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@Service("shoppingCart")
@Transactional
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    /**
     * 添加购物车
     * @param shoppingCart 购物车信息
     * @return 购物车信息
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        // 查询当前菜品是否在购物车中
        ShoppingCart dbCart = null;
        if (shoppingCart.getDishId() != null) {
            dbCart = baseMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, shoppingCart.getUserId()).eq(ShoppingCart::getDishId, shoppingCart.getDishId()));
        } else {
            dbCart = baseMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, shoppingCart.getUserId()).eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId()));
        }
        if (dbCart != null) {
            dbCart.setNumber(dbCart.getNumber() + 1);
            baseMapper.updateById(dbCart);
        } else {
            shoppingCart.setNumber(1);
            baseMapper.insert(shoppingCart);
            dbCart = shoppingCart;
        }
        return dbCart;
    }

    /**
     * 购物车数量减1
     * @param shoppingCart 购物车信息
     * @return 是否成功
     */
    @Override
    public R<ShoppingCart> sub(ShoppingCart shoppingCart) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, BaseContext.getCurrentUser());
        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart dbCart = baseMapper.selectOne(queryWrapper);
        dbCart.setNumber(dbCart.getNumber() - 1);
        baseMapper.updateById(dbCart);
        return R.success(dbCart);
    }
}
